import logging
import random
import re
from datetime import datetime

from flask import current_app
from flask import json, jsonify
from flask import make_response
from flask import request
from flask import session

from info import redis_store, db
from info.models import User
from utils.captcha.captcha import captcha
from utils.response_code import RET
from . import passport_blue

@passport_blue.route('/logout', methods=['post'])
def logout():
    #删除登陆状态保持的session
    session.pop("user_id",None)
    session.pop("nick_name",None)

    return jsonify(errno=RET.OK,errmsg="退出成功")

@passport_blue.route('/login', methods=['post'])
def login():
    dict_data = request.json
    mobile = dict_data.get("mobile")
    password = dict_data.get("password")

    #判空
    if not all([mobile,password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    #查询数据库
    try:
        user=User.query.filter(User.mobile==mobile).first()
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询用户失败")

    if not user :
        return jsonify(errno=RET.DATAERR, errmsg="账号不存在")

    if not  user.check_passowrd(password):
        return jsonify(errno=RET.DATAERR,errmsg="密码错误")

    #设置登陆session保持
    session["user_id"] = user.id
    session["nick_name"] = user.nick_name

    #记录最后一次登陆时间
    user.last_login=datetime.now()

    return jsonify(errno=RET.OK,errmsg="登陆成功")


# 注册功能
@passport_blue.route('/register', methods=['post'])
def register():
    # 获取参数
    json_data = request.data
    dict_data = json.loads(json_data)
    mobile = dict_data.get("mobile")
    sms_code = dict_data.get("sms_code")
    password = dict_data.get("password")

    # 判断用户是否存在
    count = 0
    try:
        count = User.query.filter(User.mobile == mobile).count()
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="查询错误")

    if count > 0:
        return jsonify(errno=RET.DATAERR, errmsg="用户已存在")

    # 获取短信验证码
    redis_sms_code = redis_store.get("sms_code:%s" % mobile)

    # 判断验证码是否过期
    if not redis_sms_code:
        return jsonify(errno="RET.DATAERR", errmsg="短信验证码过期")

    # 判断验证码是否匹配
    if redis_sms_code != sms_code:
        return jsonify(errno="RET.DATAERR", errmsg="短信验证码填写错误")

    try:
        user = User()
        user.nick_name = mobile
        user.password = password
        user.mobile = mobile

        db.session.add(user)
        db.session.commit()
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg="注册失败")

    #删除redis短信验证码
    redis_store.delete("sms_code:%s" % mobile)

    return jsonify(errno=RET.OK, errmsg="注册成功")


# 图片验证码
@passport_blue.route('/image_code')
def image_code():
    # 接收参数
    cur_id = request.args.get("cur_id")
    pre_id = request.args.get("pre_id")

    if not cur_id:
        return "参数不全"

    # 去重：
    if pre_id:
        redis_store.delete("image_code:%s" % pre_id)

    # 接收第三方模块的图片id，图片文本信息，图片本身
    name, text, image_code = captcha.generate_captcha()

    logging.debug("图片验证码,%s" % text)

    # 存到redis
    redis_store.set("image_code:%s" % cur_id, text, 300)

    # 创建返回体对象
    response = make_response(image_code)
    # 设置返回内容
    response.headers['Content-Type'] = 'image/png'

    return response
    # ,200,"Content-Type:image/png"


# 发送短信验证码
@passport_blue.route('/sms_code', methods=['post'])
def sms_code():
    # 获取参数
    json_data = request.data
    dict_data = json.loads(json_data)
    mobile = dict_data.get("mobile")
    image_code = dict_data.get("image_code")
    image_code_id = dict_data.get("image_code_id")

    # 判空
    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    # 判断手机格式
    if not re.match(r"1[3-9]\d{9}$", mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    # 判断验证码是否过期
    redis_image_code = redis_store.get("image_code:%s" % image_code_id)
    if not redis_image_code:
        return jsonify(error=RET.PARAMERR, errmsg="图片验证码过期")

    # 删除redis的验证码：
    redis_store.delete("image_code:%s" % image_code_id)

    if image_code.lower() != redis_image_code.lower():
        return jsonify(error=RET.DATAERR, errmsg="图片验证码错误")

    # 生成短信随机码
    sms_code = "%06d" % random.randint(0, 999999)
    logging.debug("我发验证码了,%s" % sms_code)

    # 将随机码保存到redis
    redis_store.set("sms_code:%s" % mobile, sms_code, 300)

    return jsonify(error=RET.OK, errmsg="发送成功")
